﻿using ERPWinFormWork.Product.ProductDtos;
using ERPWinFormWork.Product.ProductErrorCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERPWinFormWork.Product
{
    public partial class InventoryShow : Form
    {


        private ApiClient _apiClient;
        private int PageIndex { get; set; } = 1;
        private int PageSize { get; set; } = 15;
        private int TotalPages { get; set; } = 1;
        private int TotalSize { get; set; }

        public InventoryShow()
        {
            InitializeComponent();
            // 初始化 API 客户端（替换为你的实际 API 基础地址）
            _apiClient = new ApiClient(AppConfig.ApiBaseUrl);
            GetData();


            //// 设置占位提示为水印，不作为实际输入内容
            //textinspectionNode.Text = string.Empty;
            //textinspectionNode.WaterText = "请输产品编号";
            //textinspectionNode.SkinTxt.Text = string.Empty;
            //textinspectionNode.SkinTxt.WaterText = "请输入产品编号";

            //skinTextBox5.Text = string.Empty;
            //skinTextBox5.WaterText = "请输入产品名称";
            //skinTextBox5.SkinTxt.Text = string.Empty;
            //skinTextBox5.SkinTxt.WaterText = "请输入产品名称";

            //skinTextBox2.Text = string.Empty;
            //skinTextBox2.WaterText = "请输入BOM编号";
            //skinTextBox2.SkinTxt.Text = string.Empty;
            //skinTextBox2.SkinTxt.WaterText = "请输入BOM编号";

            //skinTextBox3.Text = string.Empty;
            //skinTextBox3.WaterText = "请输入库存上限";
            //skinTextBox3.SkinTxt.Text = string.Empty;
            //skinTextBox3.SkinTxt.WaterText = "请输入库存上限";

            //skinTextBox4.Text = string.Empty;
            //skinTextBox4.WaterText = "请输入库存下限";
            //skinTextBox4.SkinTxt.Text = string.Empty;
            //skinTextBox4.SkinTxt.WaterText = "请输入库存下限";
        }



        /// <summary>
        /// 入库信息的显示
        /// </summary>
        private async void GetData()
        {
            var parameters = new Dictionary<string, string>
                {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    { "Product_Name", this.skinTextBox5.Text },
                    //{ "Stockout_Number", this.textinspectionNode.Text }, Product_Bom
                    { "Product_Number", this.textinspectionNode.Text },
                    { "UpInventory", this.skinTextBox2.Text },
                    { "Down_Inventory", this.skinTextBox3.Text },
                    { "Product_Bom", this.skinTextBox4.Text },
                };


            var response = await _apiClient.GetAsync<ApiResult<List<InventoryDtos>>>(
                    endpoint: "Product/InventoryShow",
                    parameters: parameters
                );
            if (response != null && response.code == 200)
            {
                dgvGetDiscount.DataSource = response.pageData;
                TotalPages = response.totaCount;
                TotalSize = Convert.ToInt32(Math.Ceiling(TotalPages * 1.0 / PageSize));
                this.lblcount.Text = TotalSize.ToString();
            }
        }

        /// <summary>
        /// 上一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPrevPage_Click(object sender, EventArgs e)
        {
            if (PageIndex > 1)
            {
                PageIndex--;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }

        /// <summary>
        /// 下一页
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextPage_Click(object sender, EventArgs e)
        {
            if (PageIndex < TotalSize)
            {
                PageIndex++;
                txtCurrentPage.Text = PageIndex.ToString();
                GetData();
            }
        }



        /// <summary>
        /// 导出按钮设置
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void skinButton1_Click(object sender, EventArgs e)
        {

        }
        private async void skinButton1_Click_1(object sender, EventArgs e)
        {
            var parameters = new Dictionary<string, string>
            {
                    { "PageIndex", PageIndex.ToString() },
                    { "PageSize", PageSize.ToString() },
                    //{ "Name", this.txtDiscountName.Text.Trim() },
                    //{ "Createtime", this.dtpCreateTime.Text },
            };

            // Assuming export endpoint is Sales/DiscountExport and returns ApiResponse<string> with file path or message
            byte[] excelBytes = await _apiClient.GetBytesAsync(
            endpoint: "Product/InventoryShowGet", // 后端导出接口名（与 [HttpGet("DiscountGetExport")] 匹配）
            parameters: parameters
             );

            using (var saveDialog = new SaveFileDialog())
            {
                saveDialog.Filter = "Excel文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*"; // 只允许保存xlsx格式
                saveDialog.Title = "保存折扣方案导出文件";
                // 默认文件名：与后端一致（带时间戳，避免重复）
                saveDialog.FileName = $"产品库存信息_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
                saveDialog.RestoreDirectory = true; // 打开时默认显示上次保存的路径

                // 若用户选择了保存路径
                if (saveDialog.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        // 将二进制流写入本地文件（完成保存）
                        System.IO.File.WriteAllBytes(saveDialog.FileName, excelBytes);

                        // 导出成功提示 + 可选打开文件
                        DialogResult openChoice = MessageBox.Show(
                            $"导出成功！\n文件已保存到：\n{saveDialog.FileName}\n是否立即打开文件？",
                            "导出成功",
                            MessageBoxButtons.YesNo,
                            MessageBoxIcon.Information
                        );

                        if (openChoice == DialogResult.Yes)
                        {
                            // 用系统默认程序（如WPS/Office）打开Excel
                            System.Diagnostics.Process.Start(saveDialog.FileName);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        // 处理“无保存权限”错误（如选择C盘根目录）
                        MessageBox.Show("导出失败：没有文件保存权限！请选择桌面或其他有权限的路径。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    catch (System.IO.IOException ex)
                    {
                        // 处理“文件被占用”错误（如Excel已打开）
                        MessageBox.Show($"导出失败：文件被占用！\n原因：{ex.Message}\n请先关闭已打开的同名Excel文件。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }

        /// <summary>
        /// 查询按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void searchoutproduct_Click(object sender, EventArgs e)
        {
            GetData();
        }

        /// <summary>
        /// 重置按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnqclick_Click(object sender, EventArgs e)
        {
            GetData();
        }

    }
}
